package game.views;

import hx.events.Event;
import hx.display.ArrayCollection;
import hx.ui.UIManager;
import hx.display.Box;

using Reflect;

/**
 * 属性选择项组件
 */
@:build(hx.macro.UIBuilder.build("assets/views/ConfigSetItem.xml"))
class ConfigSetItem extends Box implements IMenuItem {
	private var __data:ArrayCollection;

	private var __index:Int = 0;

	public var fieldName = "text";

	dynamic public function onOk():Void {};

	override function onBuildUI() {
		super.onBuildUI();
		this.left.clickEvent = () -> {
			__index--;
			if (__index < 0)
				__index = __data.length - 1;
			this.setIndex(__index);
		}
		this.right.clickEvent = () -> {
			__index++;
			if (__index >= __data.length)
				__index = 0;
			this.setIndex(__index);
		}
	}

	/**
	 * 设置选择项
	 * @param bool 
	 */
	public function setSelected(bool:Bool):Void {
		this.bg.data = UIManager.getBitmapData(!bool ? "GameUIAtlas:config_bg" : "GameUIAtlas:config_bg_red");
		this.bg2.data = UIManager.getBitmapData(bool ? "GameUIAtlas:config_bg2" : "GameUIAtlas:config_bg1");
	}

	/**
	 * 设置显示数据
	 * @param data 
	 */
	public function setData(data:ArrayCollection):Void {
		__data = data;
		this.setIndex(0);
	}

	public var data(never, set):String;

	private function set_data(value:String):String {
		this.setData(new ArrayCollection(value.split(",").map(a -> {
			{
				text: a,
				value: a
			};
		})));
		return value;
	}

	public var title(get, set):String;

	private function get_title():String {
		return this.titleText.data;
	}

	private function set_title(value:String):String {
		this.titleText.data = value;
		return value;
	}

	public function onNext():Void {
		this.right.clickEvent();
	}

	public function onPrev():Void {
		this.left.clickEvent();
	}

	public function setIndex(index:Int):Void {
		__index = index;
		labelText.data = selectedItem.getProperty(fieldName);
		this.dispatchEvent(new Event(Event.CHANGE));
	}

	public var selectedIndex(get, never):Int;

	private function get_selectedIndex():Int {
		return __index;
	}

	public var selectedItem(get, never):Dynamic;

	private function get_selectedItem():Dynamic {
		return __data.source[__index];
	}
}
